<template>
  <el-dialog
    title="添加分类"
    :visible.sync="visible"
    :before-close="handleClose"
  >
    <el-form :model="cate" :rules="$rules.cate" ref="cateRuleForm">
      <el-form-item
        label="分类名称"
        :label-width="formLabelWidth"
        prop="cat_name"
      >
        <el-input v-model="cate.cat_name"></el-input>
      </el-form-item>
      <el-form-item label="父级分类" :label-width="formLabelWidth" >
        <div class="block">
          <el-cascader
            ref="cateForm"
            style="width: 100%"
            :options="categoriesForm"
            :props="categoriesProps"
            clearable
          ></el-cascader>
        </div>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleAddCategories">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
export default {
  props: {
    categoriesVisible: {
      type: Boolean,
      default: false,
    },
    categoriesForm: {
      type: Array,
      default: function () {
        return [];
      },
    },
  },
  data() {
    return {
      visible: false,
      formLabelWidth: "80px",
      cate: {
        cat_name:''
      },
      categoriesProps: {
        checkStrictly: true,
        value: "cat_name",
        label: "cat_name",
        expandTrigger: "hover",
      },
    };
  },
  methods: {
    async handleAddCategories() {
      await this.$refs.cateRuleForm.validate();
      let temp = this.$refs.cateForm.getCheckedNodes()[0];
      let arg = {};
      if (!temp) {
        arg = {
          cat_pid: 0,
          cat_name: this.cate.cat_name,
          cat_level: 0,
        };
      } else {
        arg = {
          cat_pid: temp.data.cat_id,
          cat_name: this.cate.cat_name,
          cat_level: temp.data.cat_level + 1,
        };
      }
      let result = await this.$api.addCategories(arg);
      if (result == "error") return;
      this.$message.success("分类添加成功");
      this.$emit("handleAddCategories", false);
      this.cate.cat_name = "";
      this.$refs.cateForm.panel.clearCheckedNodes();
    },
    handleClose() {
      this.cate.cat_name = "";
      this.$refs.cateForm.panel.clearCheckedNodes();
      this.$emit("update:categoriesVisible", false);
    },
  },
  watch: {
    categoriesVisible() {
      this.visible = this.categoriesVisible;
    },
  },
};
</script>